import { VFC, useState, useEffect, useRef,PropsWithChildren } from "react";
import { Table, Pagination, Button } from 'antd';
import { withRouter, useHistory } from 'react-router-dom';
import cls from './index.module.less';
import { RcIf } from 'zw-components';
import { Delete } from './buttons/delete';
import { Edit } from './buttons/edit';
import { View } from './buttons/view';
type PageProps = {
    pageSize?: number;
    currentPage?: number;
    onPageChange?: (page: number, pageSize: number) => void;
    total?: number;
}
type TableListPageProps = {
    column: any[];
    data: any[];
    rowKey?: string;
}
const footerHeight  = 60;
export const TableListPage: VFC<TableListPageProps & PageProps> = (props) => {

    const [maxPage, setMaxPage] = useState(100);
    const [tableBodyHeight, setTableBodyHeight] = useState(500);
    const [tableHeaderHeight, setTableHeaderHeight] = useState(55);
    const containerRef: any =  useRef<HTMLElement>();
    const [_, reload] = useState({});
    const {pageSize = 20, currentPage = 1, onPageChange = ()=>{}, total=100} = props;
    useEffect(() => {
        if(!containerRef.current) return;
        let _tableBodyHeight = (containerRef.current as HTMLElement).clientHeight - tableHeaderHeight - footerHeight - 1;
        setTableBodyHeight(_tableBodyHeight)
    }, [containerRef]);
    useEffect(() => {
        setMaxPage(Math.ceil(total / pageSize));
    }, [total, pageSize]);
    return (
        <div ref={containerRef} className={cls.container}>
            <div className={cls.body}>
                <Table rowKey={props.rowKey ? props.rowKey : 'id'} columns={props.column} dataSource={props.data} pagination={false} scroll={{scrollToFirstRowOnChange: true, y: tableBodyHeight}}/>
            </div>
            <RcIf value={maxPage > 1}>
                <div className={cls.footer} >
                    <Pagination  current={currentPage} pageSize={props.pageSize} onChange={onPageChange}  total={total} />
                </div>
            </RcIf>
        </div>
    );
}

const Normal: VFC<PropsWithChildren<{onClick: () => void}>> = (props) => {
    return (
        <Button onClick={props.onClick} type="link">{props.children}</Button>
    );
}
const Link: VFC<PropsWithChildren<{to: string}>> = (props) => {
    const history = useHistory();
    return (
        <Button onClick={() => {
            history.push(props.to)
        }} type="link">{props.children}</Button>
    );
}
export const Operate = {
    View: View,
    Edit: Edit,
    Delete: Delete,
    Normal: Normal,
    Link: Link
}